//
//  MineViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/7.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "MineViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <UMShare/UMShare.h>
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "MineTableViewCell.h"
#import "CollectTableViewController.h"
#import "MineInfoTableViewController.h"
#import "UpdateViewController.h"
#import "NetManager.h"
#import "User.h"
@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource, MineInfoBindDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *mineFuncTitles;
@property (nonatomic, strong) NSArray *mineFuncImgs;
@property (nonatomic, strong) NSDictionary *userInfo;
@property (nonatomic, strong) NSDictionary *aboutUsInfo;
@end

@implementation MineViewController


#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.mineFuncTitles = @[@"我的收藏", @"浏览历史", @"关于我们"];
    self.mineFuncImgs = @[@"yourCollects", @"scanHistory", @"aboutUs"];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self fetchData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return self.mineFuncTitles.count;
    }
    else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableViewCell *cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mineInfoCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithRed:79/255. green:198/255. blue:65/255. alpha:1];
        if ([self.userInfo safeObjectForKey:@"id"]) {
            cell.infoNameLabel.text = [NSString stringWithFormat:@"你的ID:%@",[self.userInfo safeObjectForKey:@"id"]];
        }
        __weak typeof(cell) weakCell = cell;
        cell.infoImgView.layer.masksToBounds = YES;
        NSString *avatarAddressStr = [self.userInfo safeObjectForKey:@"avatar"];
#if DEBUG
        avatarAddressStr = [avatarAddressStr stringByReplacingOccurrencesOfString:@"https" withString:@"http"];
#else
#endif
        [cell.infoImgView sd_setImageWithURL:[NSURL URLWithString:avatarAddressStr] placeholderImage:[UIImage imageNamed:@"headPortrait"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            NSLog(@"头像的尺寸：%@",NSStringFromCGSize(image.size));
            weakCell.infoImgView.layer.cornerRadius = weakCell.infoImgView.bounds.size.width/2;
        }];
        if ([[self.userInfo safeObjectForKey:@"is_bind_phone"] isEqual:@1]) {
            [cell.phoneBtn setTitle:[self.userInfo safeObjectForKey:@"phone_number"] forState:UIControlStateNormal];
            cell.phoneBtn.userInteractionEnabled = NO;
        }
        if ([[self.userInfo safeObjectForKey:@"wx_is_bind"] isEqual:@1]) {
            [cell.wechatBtn setTitle:[self.userInfo safeObjectForKey:@"name"] forState:UIControlStateNormal];
            cell.wechatBtn.userInteractionEnabled = NO;
        }
        cell.delegate = self;
    } else if(indexPath.section == 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mineFuncCell" forIndexPath:indexPath];
        cell.funcLabel.text = [self.mineFuncTitles safeObjectAtIndex:indexPath.row];
        cell.funcImgView.image = [UIImage imageNamed:[self.mineFuncImgs safeObjectAtIndex:indexPath.row]];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"exitCell" forIndexPath:indexPath];
        cell.versionLabel.text = [NSString stringWithFormat:@"版本：%@",[[NetManager defaultNetManager] app_version]];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    }else {
        return 4.0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        MineInfoTableViewController *mineInfoVC = [MineInfoTableViewController mineInfoVCFromStoryBoard];
        mineInfoVC.userInfo = self.userInfo;
        [self.navigationController pushViewController:mineInfoVC animated:YES];
    }
    if(indexPath.section == 1) {
        CollectTableViewController *collectVC = [CollectTableViewController collectVCFromStoryBoard];
        if (indexPath.row == 0) {
            collectVC.type = INTERACTIVETYPE_COLLECT;
            collectVC.title = @"我的收藏";
        } else if (indexPath.row == 1) {
            collectVC.type = INTERACTIVETYPE_SCAN;
            collectVC.title = @"最近浏览";
        } else if (indexPath.row == 2) {
            UIViewController *vc = [[UIViewController alloc] init];
            NSString *strHTML = [self.aboutUsInfo safeObjectForKey:@"content"];
            UIWebView *webView = [[UIWebView alloc] initWithFrame:vc.view.bounds];
            [webView loadHTMLString:strHTML baseURL:nil];
            [vc.view addSubview:webView];
            vc.title = [self.mineFuncTitles safeObjectAtIndex:indexPath.row];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
         else {
            return;
        }
        [self.navigationController pushViewController:collectVC animated:YES];
    }
}
#pragma mark - MineInfoBindDelegate
- (void)bindType:(BINDTYPE)type {
    if (type == BINDTYPE_Phone) {
        UpdateViewController *updateVC = [UpdateViewController updateVCFromStoryBoard];
        updateVC.type = UPDATETYPE_Phone;
        [self presentViewController:updateVC animated:YES completion:nil];
    }
    if (type == BINDTYPE_Wechat) {
        [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
    }
}
#pragma mark - private
- (void)fetchData {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/user_info" params:@{@"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"info"]) {
            self.userInfo = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"info"];
            self.aboutUsInfo = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"guanyu"];
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)updateInfo:(NSDictionary *)info {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/editinfo" params:info success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"code"] integerValue] == 1) {
            [self fetchData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
        
        UMSocialUserInfoResponse *resp = result;
        
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        NSLog(@" uniond: %@", resp.unionId);
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.unionGender);
        
        [self updateInfo:@{@"uid":[User userID],
                           @"wechatOpenID":resp.openid,
                           @"wechatUnionID":resp.unionId,
                           @"wechatName":resp.name
                           }];
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
    }];
}
#pragma mark - getter
- (NSDictionary *)userInfo {
    if (!_userInfo) {
        _userInfo = nil;
    }
    return _userInfo;
}
@end
